package com.story.rpc.transmission.socket.server;

import com.story.rpc.dto.RpcReq;
import com.story.rpc.dto.RpcResp;
import com.story.rpc.handler.RpcReqHandler;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

@Slf4j
@AllArgsConstructor
public class SocketReqHandler implements Runnable{
    private final Socket socket;
    private final RpcReqHandler rpcReqHandler;

    @SneakyThrows
    @Override
    public void run() {
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        RpcReq req = (RpcReq) ois.readObject();
        log.info("receive request: {}", req);

        // 调用rpcReq中的接口实现类的方法
        Object data = rpcReqHandler.invoke(req);

        RpcResp<?> rpcResp = RpcResp.success(req.getReqId(),data);

        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(rpcResp);
        oos.flush();
    }
}
